﻿namespace GreenIsomer.Data.Entities.Ddl {
	using System;
	using System.Xml.Serialization;

	[Serializable]
	[XmlInclude(typeof(BooleanColumn))]
	[XmlInclude(typeof(DateTimeColumn))]
	[XmlInclude(typeof(GuidColumn))]
	[XmlInclude(typeof(NumericColumn))]
	[XmlInclude(typeof(StringColumn))]
	public class DefinitionData {
		
		[NonSerialized]
		private ColumnCollection columns;

		[NonSerialized]
		private RecordCollection records;

		public DefinitionData() {
			columns = new ColumnCollection();
			records = new RecordCollection();
		}

		[XmlAttribute("Table")]
		public string TableName { get; set; }

		[XmlElement("Column")]
		public ColumnCollection Columns {
			get { return columns; }
		}

		[XmlElement("Record")]
		public RecordCollection Records {
			get { return records; }
		}

		public virtual void WriteCreateScript(DdlWriter writer, TableCollection tables) {

			Table table = tables.Find(TableName);
			if(table == null) return;

			int columnCount = columns.Count;
			if(columnCount == 0) return;

			foreach(Record record in Records) {

				ValueCollection values = record.Values;

				int valueCount = values.Count;
				if(valueCount == 0) continue;

				int count = Math.Min(columnCount, valueCount);

				writer.StartNewLine();
				writer.WriteScript("INSERT INTO");

				writer.AddSpace();
				writer.WriteSchemaPrefix(table.Schema);
				writer.WriteName(table.Name);
				writer.AddSpace();

				writer.WriteScript("(");

				for(int i = 0; i < count; i++) {
					if(i != 0) writer.WriteScript(",");
					writer.WriteName(columns[i].Name);
				}

				writer.WriteScript(") VALUES (");

				for(int i = 0; i < count; i++) {
					if(i != 0) writer.WriteScript(",");
					columns[i].WriteScript(writer, values[i]);
				}

				writer.WriteScript(");");

			}

		}

	}

}